#!/bin/bash
usage()
{
  echo "USAGE: $0 [new|prepare|status|swap] repository_root"
  exit 1
}

versioning=svn
args=()
lftp_command=lftp
ftp_verify_ssl_certificate=yes

# Load global frt config
if [ -f $HOME/.frt ]
then
  source $HOME/.frt
fi

# Parse options
while [[ $1 ]]
do
  case $1 in
    -h|--help|-\?) 
      usage
      exit 0
    ;;

    # Versioning
    -V) 
      if (($# > 1))
      then
        versioning=$2
        shift
      else
        echo "-V requires an argument" 1>&2
        exit 1
      fi
    ;;

    # Invalid
    -*) 
      echo "invalid option: $1" 1>&2
      usage
      exit 1
    ;;

    # Arguments
    *)
      args[${#args[@]}]=$1
    ;;
  esac

  shift
done

# Check for parameters
if [[ ${#args} -lt 2 ]]
then
  usage
fi

# Check for lftp
if [[ ! `type -t $lftp_command` ]]
then
  echo "frt requires lftp."
  echo "Run:"
  # apt-get
  if [[ `type -t apt-get` ]]
  then
    echo "  sudo apt-get install lftp"
  # yum
  elif [[ `type -t yum` ]]
  then
    echo "  sudo yum search lftp"
    echo "  sudo yum install lftp"
  # pacman
  elif [[ `type -t packman` ]]
  then
    echo "  pacman -Syy"
    echo "  pacman -Syu"
    echo "  pacman -S lftp"
  # all others
  else
    echo "  wget http://ftp.yars.free.net/pub/source/lftp/lftp-4.1.3.tar.gz"
    echo "  tar -zxvf lftp-4.1.3.tar.gz"
    echo "  cd lftp-4.1.3"
    echo "  ./configure"
    echo "  make"
    echo "  sudo make install"
  fi
  exit 2
fi

if [ $versioning != svn ] && [ $versioning != git ]
then
  echo "FRT doesn't work with the '$versioning' versioning control"
  exit
fi

root_dir="$( cd -P "$( dirname "$0" )" && pwd )"
source $root_dir/lib/global.sh
source $root_dir/lib/$versioning.sh

if [ -f $root_dir/scripts/${args[0]}.sh ]
then
  source $root_dir/scripts/${args[0]}.sh
else
  usage
fi

exit 0

